﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace GoodStuff.Web.Controls
{
    public static class PageTools
    {
        /// <summary>
        /// Binds the given Textbox to a button. When the enterkey is pressed (when focus is on that textbox) the button clicked.
        /// </summary>
        /// <param name="page">The Page-object</param>
        /// <param name="TextBoxToTie"></param>
        /// <param name="ButtonToTie"></param>
        public static void TieButton(this Page page, Control TextBoxToTie, Control ButtonToTie)
        {
            // Init jscript

            string jsString = "";

            // Check button type and get required jsscript

            if (ButtonToTie is LinkButton || ButtonToTie is ImageButton)
            {
                jsString = "if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {"
                           + page.ClientScript.GetPostBackClientHyperlink(ButtonToTie, "") + ";return false;} else return true;";
            }
            else
            {
                jsString = "if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {document."
                           + "forms[0].elements['" + ButtonToTie.UniqueID.Replace(":", "_") + "'].click();return false;} else return true; ";
            }

            // Attach jscript to the onkeydown attribute-we have to cater for HtmlControl or WebControl

            if (TextBoxToTie is HtmlControl)
            {
                ((HtmlControl)TextBoxToTie).Attributes.Add("onkeydown", jsString);
            }
            else if (TextBoxToTie is WebControl)
            {
                ((WebControl)TextBoxToTie).Attributes.Add("onkeydown", jsString);
            }
        }
    }
}
